package com.wzgl.core.webmagic;

import java.io.File;
import java.net.URL;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.qcloud.cos.request.UploadFileRequest;
import com.wzgl.core.config.plugin.COSClientPlugin;

public class MagicUtils {
	private static Log logger=Log.getLog(MagicUtils.class);
	static String localPath = PathKit.getWebRootPath() + "/upload/";
	/** 
     * 下载图片到本地 
     * @param picUrl 图片Url 
     * @param localPath 本地保存图片地址 
     * @return 
     */  
    public static String downloadPic(String picUrl){  
        String filePath = null; 
        File f = null;
        String url = null;  
        
        try {    
            URL httpurl = new URL(picUrl);    
            String fileName = getFileNameFromUrl(picUrl);    
            filePath = localPath + fileName;  
            f = new File(filePath);    
            FileUtils.copyURLToFile(httpurl, f);   
            
            UploadFileRequest ur = new UploadFileRequest(PropKit.use("wzgl_config.txt").get("bucket"),"/"+fileName, f.toString());
            COSClientPlugin cos = new COSClientPlugin();
            String mes ="";
            if(COSClientPlugin.cosClient == null){
            	cos.start();
            	mes = cos.cosClient(ur);
            }else{
            	mes = COSClientPlugin.cosClient(ur);
            }
			//System.out.println(mes);
			JSONObject comMsg = JSONObject.parseObject(mes);
			//解析云存储返回信息
			int code = comMsg.getIntValue("code");
			//返回数据
			String obj = comMsg.getString("data");
			if(code == 0){
				JSONObject data = JSONObject.parseObject(obj);
				url = data.getString("source_url");
			}else{
				url  = null;
			}
			//------------------保存到云存储-------------------------
			f.delete();
        } catch (Exception e) {    
            logger.info(e.getMessage());    
            return null;    
        }finally{
        	if(f != null){
        		f.delete();
        	}
        }
        return url;  
    }  
    /** 
     * 根据url获取文件名 
     * @param url  
     * @return 文件名 
     */  
    public static String getFileNameFromUrl(String url){    
        //获取后缀  
        String sux = url.substring(url.lastIndexOf("."));  
        if(sux.length() > 4){  
            sux = ".jpg";  
        }  
        int i = (int)(Math.random()*1000);  
        //随机时间戳文件名称  
        String name = new Long(System.currentTimeMillis()).toString()+ i + sux;   
        return name;    
    }  
}
